package com.itehima.filter;


import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.file.Path;

@Component
@Slf4j
public class AdminAuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest req = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse resp = exchange.getResponse();
        //白名单
        String path = req.getURI().getPath();
        log.debug("请求的地址：{}", path);
        if (path.startsWith("/admin/login")){
            return chain.filter(exchange);
        }
        //获取url请求地址token
        String token = req.getHeaders().getFirst("token");
        //判断地址是否有后台登录地址
        if (!StringUtils.isEmpty(token)){
            //检验token有效性
            int result = AppJwtUtil.verifyToken(token);
            //有效期放行
            if (SystemConstants.JWT_OK==result){
                return chain.filter(exchange);
            }
        }
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        return resp.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
